﻿using System;
using System.Collections.Generic;
using System.Text;

using Newtonsoft.Json;

using Utils;

namespace System
{
    /// <summary>
    /// 脱敏
    /// </summary>
    public class DesensitizeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsEquivalentTo(typeof(string));
        }

        public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        {
            return serializer.Deserialize(reader, objectType) ?? existingValue;
        }

        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            var str = value?.ToString() ?? "";
            if (str.IsNullOrEmpty())
            {
                serializer.Serialize(writer, value);
            }
            else if (str.IsMobile())
            {
                serializer.Serialize(writer, str.HideMobile());
            }
            else if (str.IsBankCardNo())
            {
                serializer.Serialize(writer, str.BeautifySplit().HideSome());
            }
            else if (str.IsChinese())
            {
                serializer.Serialize(writer, str.HideSome(1, 1));
            }
            else
            {
                serializer.Serialize(writer, str.HideSome(str.Length / 5, str.Length / 5));
            }
        }
    }
}
